<?php
require_once __DIR__.'/./MessageAction.php';

use im\MessageAction;

$msg_action = new MessageAction();
$serv = new swoole_websocket_server("1.1.1.1", 111);

//config
$serv->set(array(
    'worker_num' => 4,    //worker process num
    'backlog' => 128,   //listen backlog
    'max_request' => 500,
    'dispatch_mode'=>2,
    'heartbeat_idle_time' => 9,
    'heartbeat_check_interval' => 3,
    'open_tcp_keepalive'=>1
));


$serv->on('Open', function($server, $req){
    echo "\n\tconnection open: ".$req->fd."\n\t";
});

$serv->on('Message', function($server, $frame) use ($msg_action){
    
    if(strlen(trim($frame->data)) == 0){
        return true;
    }
    
    $data = json_decode($frame->data,true);
    $action = $data['action'];

    if(method_exists($msg_action, $action)){
        $msg_action->$action($data['data'],$server,$frame);
    }else{
        file_put_contents('./error_logs', 'Action:'.$action.'无法找到！',FILE_APPEND);
    }
    
});

//定时器，检查当前在线FD
$serv->on('WorkerStart', function($server,$worker_id) {
    if($worker_id == 0){
        $server->tick(1000,function() use ($server,$worker_id){
            echo "\n\tProcess:".$worker_id.'|Connections:'.count($server->connections)."\n\t";
        });
    }
});

$serv->on('close',array($msg_action,'on_close'));

$serv->start();